package com.shuma.approval.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuma.approval.constant.*;
import com.shuma.approval.dto.R;
import com.shuma.approval.entity.GoodsBaseInfo;
import com.shuma.approval.entity.OperatorLog;
import com.shuma.approval.exception.GoodNotFoundException;
import com.shuma.approval.mapper.GoodsBaseInfoMapper;
import com.shuma.approval.service.ApprovalService;
import com.shuma.approval.service.IGoodsBaseInfoService;
import com.shuma.approval.service.IOperatorLogService;
import com.shuma.approval.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@SofaService(interfaceType = ApprovalService.class, uniqueId = "${service.unique.id}", bindings = { @SofaServiceBinding(bindingType = "bolt") })
public class ApprovalServiceImpl implements ApprovalService {


    @Autowired
    private IGoodsBaseInfoService goodsBaseInfoService;
    @Autowired
    private IOperatorLogService operatorLogService;
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsBaseInfoMapper goodsBaseInfoMapper;

    private static final Logger LOG = LoggerFactory.getLogger(ApprovalServiceImpl.class);


    /**
     * 发起审核
     */
    @Transactional
    public R add(Long id, String remark) {
        GoodsBaseInfo good = goodsBaseInfoService.getById(id);  //查询物品
        if (good == null) {
            //物品不存在
            throw new GoodNotFoundException(MessageConstant.GOOD_NOT_FOUND);
        }
        //获取商品小二操作状态
        int status = good.getGoodsOwnerStatus();
        //已编辑才能提交审核
        if (status == GoodsOwnerStatusConstant.Edited) {
            goodsBaseInfoService.update()
                    .set("goods_owner_status", GoodsOwnerStatusConstant.Submitted)
                    .eq("goods_base_id", id).update();
            //记录操作日志
            savaOperatorLog(id, remark, OperatorStatusConstant.ADD_APPROVAL,
                    Long.valueOf((String) StpUtil.getLoginId()));
            return R.ok();
        }
        return R.fail(MessageConstant.OPERATION_ERROR);
    }

    /**
     * 通过审核
     */
    @Override
    @Transactional
    public R pass(Long id, String remark) {
        GoodsBaseInfo good = goodsBaseInfoService.getById(id);        //查询物品
        if (good == null) {
            //物品不存在
            throw new GoodNotFoundException(MessageConstant.GOOD_NOT_FOUND);
        }
        int goodsOwnerStatus = good.getGoodsOwnerStatus();   //获取商品小二操作状态
        int goodsCheckStatus = good.getGoodsCheckStatus();   //商品审核状态
        if (goodsOwnerStatus == GoodsOwnerStatusConstant.Submitted
                && goodsCheckStatus == GoodsCheckStatusConstant.NOT_APPROVAL)
        {
            goodsBaseInfoService.update()
                    .set("goods_check_status", OnlineStatusConstant.IS_ONLINE)
                    .eq("goods_base_id", id).update();
            //记录操作日志
            savaOperatorLog(id, remark, OperatorStatusConstant.PASS_APPROVAL,
                    Long.valueOf((String) StpUtil.getLoginId()));
            //获取物品的上线时间
            LocalDateTime onlineTime = good.getOnlineTime();
            //上线时间在现在时间之前，直接上线
            if (onlineTime.isBefore(LocalDateTime.now())) {
                goodsBaseInfoService.update()
                        .set("goods_online_status", OnlineStatusConstant.IS_ONLINE)
                        .eq("goods_base_id", id).update();
                //记录操作日志
                savaOperatorLog(id, MessageConstant.AUTO_ONLINE, OperatorStatusConstant.GO_ONLINE,
                        Long.valueOf((String) StpUtil.getLoginId()));
            }else {
                //上线时间在现在时间之后
                LocalDateTime now= LocalDateTime.now();
                // 计算两个时间之间的 Duration
                Duration duration = Duration.between(now, onlineTime);

                // 获取两个时间之间相差的秒数
                long secondsDifference = duration.getSeconds();
                LOG.info("上线时间和现在时间相差{}秒", secondsDifference);

                //存到redis自动上线
                stringRedisTemplate.opsForValue().set(RedisConstants.AUTO_TO_ONLINE+id,
                        String.valueOf(onlineTime),secondsDifference, TimeUnit.SECONDS);
            }
            //存redis自动下线
            //获取物品的下线时间
            LocalDateTime offlineTime = good.getExpireTime();

            LOG.info("商品上线时间{}，下线时间{}", onlineTime, offlineTime);

            LocalDateTime now= LocalDateTime.now();
            // 计算两个时间之间的 Duration
            Duration duration = Duration.between(now, offlineTime);
            // 获取两个时间之间相差的秒数
            long secondsDifference = duration.getSeconds();
            LOG.info("下线时间和现在时间相差{}秒", secondsDifference);
            //存到redis自动下线
            stringRedisTemplate.opsForValue().set(RedisConstants.AUTO_TO_OFFLINE+id,
                    String.valueOf(offlineTime),secondsDifference, TimeUnit.SECONDS);
            return R.ok();
        }
        return R.fail(MessageConstant.OPERATION_ERROR);
    }

    /**
     * 审核驳回
     */
    @Override
    @Transactional
    public R out(Long id, String remark) {
        GoodsBaseInfo good = goodsBaseInfoService.getById(id);        //查询物品
        if (good == null) {
            //物品不存在
            throw new GoodNotFoundException(MessageConstant.GOOD_NOT_FOUND);
        }
        //获取商品小二操作状态
        int goodsOwnerStatus = good.getGoodsOwnerStatus();
        //商品审核状态
        int goodsCheckStatus = good.getGoodsCheckStatus();
        if (goodsOwnerStatus == GoodsOwnerStatusConstant.Submitted
                && goodsCheckStatus == GoodsCheckStatusConstant.NOT_APPROVAL) {
            goodsBaseInfoService.update()
                    .set("goods_check_status",GoodsCheckStatusConstant.OUT_APPROVAL)
                    .set("goods_owner_status",GoodsOwnerStatusConstant.Edited)
                    .eq("goods_base_id", id).update();
            //记录操作日志
            savaOperatorLog(id, remark, OperatorStatusConstant.OUT_APPROVAL, null);
            return R.ok();
        }
        return R.fail(MessageConstant.OPERATION_ERROR);
    }

    /**
     * 记录操作日志
     */
    public void savaOperatorLog(Long id, String remark, Integer status, Long ownerId) {
        if (ownerId == null) {
            ownerId = Long.valueOf((String) StpUtil.getLoginId());
        }
        OperatorLog operatorLog = new OperatorLog();
        operatorLog.setOperateId(IdUtil.getSnowflakeNextId());
        operatorLog.setOwnerId(ownerId);
        operatorLog.setCommodityId(id);
        operatorLog.setOperatorStatus(status);
        operatorLog.setRemark(remark);
        operatorLog.setOwner(userService.getById(ownerId).getUsername());
        operatorLog.setOperatorTime(LocalDateTime.now());
        //删除redis缓存
        String key = RedisConstants.OPERATORLOG + id;
        stringRedisTemplate.delete(key);

        System.out.println(operatorLog);

        operatorLogService.save(operatorLog);
    }

    // 查询所有未审核的商品
    @Override
    public R query() {
        LambdaQueryWrapper<GoodsBaseInfo> queryWrapper1 = new LambdaQueryWrapper<>();

        queryWrapper1.eq(GoodsBaseInfo::getGoodsOwnerStatus, GoodsOwnerStatusConstant.Submitted);
        queryWrapper1.eq(GoodsBaseInfo::getGoodsCheckStatus, GoodsCheckStatusConstant.NOT_APPROVAL);

        List<GoodsBaseInfo> baseInfoList = goodsBaseInfoMapper.selectList(queryWrapper1);
        return R.ok(baseInfoList);
    }
}
